package com.example.sjkks.controller;

import com.example.sjkks.entity.Student;
import com.example.sjkks.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "http://localhost:8081")
public class StudentController {

    @Autowired
    private StudentMapper studentMapper;

    @Transactional
    @PostMapping("/students")
    public ResponseEntity<Object> applyScholarship(@RequestBody Student student) {
        try {
            // 计算总分数
            if ("研二".equals(student.getGrade())) {
                int totalScore = student.getAcademicScore() + student.getPoliticalScore() + student.getResearchScore() + student.getServiceScore();
                student.setTotalScore(totalScore);
            } else if ("研三".equals(student.getGrade())) {
                int totalScore = student.getPoliticalScore() + student.getResearchScore() + student.getServiceScore();
                student.setTotalScore(totalScore);
            }

            // 保存学生申请信息
            studentMapper.save(student);
            return ResponseEntity.ok("申请已提交");
        } catch (Exception e) {
            e.printStackTrace(); // 打印异常信息
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("提交申请时出错");
        }
    }

    @Transactional
    @GetMapping("/students")
    public ResponseEntity<List<Student>> getAllStudents() {
        try {
            List<Student> students = studentMapper.findAll();
            return ResponseEntity.ok(students);
        } catch (Exception e) {
            e.printStackTrace(); // 打印异常信息
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}
